package www.wxwnb.clerk.ui.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import www.wxwnb.clerk.R;
import www.wxwnb.clerk.adapter.ResultQueryAdapter;
import www.wxwnb.clerk.base.BaseActivity;
import www.wxwnb.clerk.decoration.Divider12ItemDecoration;
import www.wxwnb.clerk.http.HttpMethods;
import www.wxwnb.clerk.http.HttpService;
import www.wxwnb.clerk.http.entity.MsgQueryBean;
import www.wxwnb.clerk.http.entity.ResultQueryBean;
import www.wxwnb.clerk.utils.Customer;
import www.wxwnb.clerk.utils.TimeUtil;

public class MsgQueryActivity extends BaseActivity {

    private static final String TAG = "MsgQueryActivity";

    private ImageButton ibtnBack;
    private TextView mStartTime;
    private TextView mEndTime;
    private ImageButton mClear;
    private RecyclerView mRecyclerView;

    private DatePickerDialog mEndDatePickerDialog;
    private int index = 1;

    private SpringView mSpringView;
    private Context mContext;
    private List<ResultQueryBean.DataBean.PageRecordsBean> dataList = new ArrayList();
    private Handler mHandler = new Handler();
    private ResultQueryAdapter mResultQueryAdapter;
    private String mStartTime1;
    private String mEndTime1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg_query);
    }

    @Override
    protected void initView() {
        mContext = this;
        findViewById(R.id.im_back_include).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        TextView title= (TextView) findViewById(R.id.open_include);
        title.setText(R.string.msg_query);
        mStartTime = (TextView) findViewById(R.id.tv_start_time);
        mStartTime.setCompoundDrawablesWithIntrinsicBounds(null, null, null, setTimeViewBottomDrawable(false));
        mEndTime = (TextView) findViewById(R.id.tv_end_time);
        mEndTime.setCompoundDrawablesWithIntrinsicBounds(null, null, null, setTimeViewBottomDrawable(false));
        mClear = (ImageButton) findViewById(R.id.ibtn_clear);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_msg_query);
        mSpringView = (SpringView) findViewById(R.id.springView);
    }

    private Drawable setTimeViewBottomDrawable(boolean b) {
        Drawable drawable = null;
        if (b) {
            if (Build.VERSION.SDK_INT >= 21) {
                drawable = getResources().getDrawable(R.drawable.shape_line, null);
            } else {
                drawable = getResources().getDrawable(R.drawable.shape_line);
            }
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                drawable = getResources().getDrawable(R.drawable.shape_line_gray, null);
            } else {
                drawable = getResources().getDrawable(R.drawable.shape_line_gray);
            }
        }
        return drawable;
    }

    @Override
    public void initListener() {
        mStartTime.setOnClickListener(this);
        mEndTime.setOnClickListener(this);
        mClear.setOnClickListener(this);

        mSpringView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                //下拉刷新
                dataList.clear();
                index = 1;
                getDataFromServer(mStartTime1, mEndTime1, index);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSpringView.onFinishFreshAndLoad();
                    }
                }, 1000);
            }

            @Override
            public void onLoadmore() {
                //加载更多
                index++;
                getDataFromServer(mStartTime1, mEndTime1, index);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSpringView.onFinishFreshAndLoad();
                    }
                }, 1000);
            }
        });

    }

    @Override
    public void initData() {


        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        mSpringView.setHeader(new DefaultHeader(mContext));
        mSpringView.setFooter(new DefaultHeader(mContext));
        mSpringView.getHeaderView().setVisibility(View.GONE);
        mSpringView.getFooterView().setVisibility(View.GONE);
    }

    @Override
    public void processClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_back:
                finish();
                break;

            case R.id.tv_start_time:
                setStartTime();
                break;

            case R.id.tv_end_time:
                setEndTime();
                break;

            case R.id.ibtn_clear:
                clearTime();
                dataList.clear();
                if (mResultQueryAdapter != null) {
                    mResultQueryAdapter.notifyDataSetChanged();
                }

                mSpringView.getHeaderView().setVisibility(View.GONE);
                mSpringView.getFooterView().setVisibility(View.GONE);
                break;
        }
    }

    private void clearTime() {
        mStartTime.setText(R.string.start_time);
        mStartTime.setTextColor(getMyColor(R.color.title));
        mStartTime.setCompoundDrawablesWithIntrinsicBounds(null, null, null, setTimeViewBottomDrawable(false));
        mEndTime.setText(R.string.end_time);
        mEndTime.setTextColor(getMyColor(R.color.title));
        mEndTime.setCompoundDrawablesWithIntrinsicBounds(null, null, null, setTimeViewBottomDrawable(false));
    }

    private int getMyColor(int id) {
        int colorId = -1;
        if (Build.VERSION.SDK_INT >= 23) {
            colorId = getResources().getColor(id, null);
        } else {
            colorId = getResources().getColor(id);
        }
        return colorId;
    }

    private void setStartTime() {
        final int[] m = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, R.style.MyDatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                mStartTime.setText(String.valueOf(year) + "-" + m[month] + "-" + dayOfMonth);
                mStartTime.setTextColor(getMyColor(R.color.colorMain));
                mStartTime.setCompoundDrawablesWithIntrinsicBounds(null, null, null, setTimeViewBottomDrawable(true));
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    private void setEndTime() {
        final int[] m = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
        Calendar calendar = Calendar.getInstance();
        mEndDatePickerDialog = new DatePickerDialog(this, R.style.MyDatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                mEndTime.setText(String.valueOf(year) + "-" + m[month] + "-" + dayOfMonth);
                mEndTime.setTextColor(getMyColor(R.color.colorMain));
                mEndTime.setCompoundDrawablesWithIntrinsicBounds(null, null, null, setTimeViewBottomDrawable(true));
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        mEndDatePickerDialog.show();
        mEndDatePickerDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                checkTimeOver();
            }
        });
    }

    private void checkTimeOver() {
        if (mStartTime.getText().toString().equals(getResources().getString(R.string.start_time)) || mEndTime.getText().toString().equals(getResources().getString(R.string.end_time))) {
            Toast.makeText(this, R.string.please_to_choose_time, Toast.LENGTH_SHORT).show();
            return;
        }
        mStartTime1 = TimeUtil.dateOrString2Timestamp(mStartTime.getText().toString());
        mEndTime1 = TimeUtil.dateOrString2Timestamp(mEndTime.getText().toString());
        if (Long.parseLong(mStartTime1) <= Long.parseLong(mEndTime1)) {
            getDataFromServer(mStartTime1, mEndTime1, index);
        } else {
            Toast.makeText(this, R.string.please_to_confirm_time, Toast.LENGTH_SHORT).show();
        }
    }

    private void getDataFromServer(String startTime, String endTime, int index) {
        HttpService httpService = HttpMethods.getInstance().mRetrofit.create(HttpService.class);
        Call<ResultQueryBean> msgQuery = httpService.getResultQuery(Customer.getInstance().getJobNumber(), startTime, endTime, String.valueOf(index));
        msgQuery.enqueue(new Callback<ResultQueryBean>() {
            @Override
            public void onResponse(Call<ResultQueryBean> call, Response<ResultQueryBean> response) {
                if (response.code() == 200) {
                    if (response.body().getReturnCode() == 1) {
                        handlerResponse(response.body().getData());
                    } else {

                    }
                }
            }

            @Override
            public void onFailure(Call<ResultQueryBean> call, Throwable t) {

            }
        });
    }

    private void handlerResponse(ResultQueryBean.DataBean data) {
        if (data.getPageNum() < data.getPageSize()) {   //当前页码 总页码
            mSpringView.getHeaderView().setVisibility(View.VISIBLE);
            mSpringView.getFooterView().setVisibility(View.VISIBLE);
        } else if (data.getPageNum() < data.getPageSize()) {
            mSpringView.getHeaderView().setVisibility(View.VISIBLE);
            mSpringView.getFooterView().setVisibility(View.GONE);
        }

        dataList.addAll(data.getPageRecords());
        if (mResultQueryAdapter == null) {
            mResultQueryAdapter = new ResultQueryAdapter(this, dataList);
            mRecyclerView.setAdapter(mResultQueryAdapter);
        } else {
            mResultQueryAdapter.setData(dataList);
        }

//        mRecyclerView.addItemDecoration(new Divider12ItemDecoration());
    }

}
